package com.mmlc.meimei.lichengkongjian.brand;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.httputil.EntryPageName;
import com.androidnetframe.responsejavabean.RequestError;
import com.androidnetframe.utils.LogUtils;
import com.mmlc.businessutils.MyShareUtils;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.Adapter.RecycGridAdapter;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.been.Condition;
import com.mmlc.meimei.lichengkongjian.classify.ProductInfoActivity;
import com.mmlc.meimei.lichengkongjian.customview.LabelFlowLayout;
import com.mmlc.meimei.lichengkongjian.customview.SwipeRecyclerView;
import com.mmlc.network.filter.GoodsListRequestFilter;
import com.mmlc.network.responsebean.GoodsListResponseBean;
import com.mmlc.utils.AppUtils;
import com.mmlc.utils.ToastUtils;
import com.mmlc.utils.ViewUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class BrandInfoActivity extends InterActivity implements AdapterView.OnItemClickListener, ConditionFragment.OnDataChangeListener {

    @Override
    protected int initContentView() {
        return R.layout.activity_brand_info;
    }

    String name, keywords, isNew;
    public String brand_id, cate_id;
    private String years;

    private String season;


    @Override
    protected void initExtra() {
        super.initExtra();

        keywords = getIntent().getStringExtra("keywords");
        isNew = getIntent().getStringExtra("is_new");
        name = getIntent().getStringExtra("name");
        brand_id = getIntent().getStringExtra("brand_id");
        cate_id = getIntent().getStringExtra("cate_id");

        if (ViewUtils.isEmpty(name) && !ViewUtils.isEmpty(keywords)) name = keywords;
        if (!ViewUtils.isEmpty(isNew) && "1".equals(isNew)) is_new = 1;
    }

    TextView tv_title,tv_verify, tv_new, tv_price, tv_condition, tv_default;
    ImageView iv_price_filtrate;
    DrawerLayout dl_condition;

    SwipeRecyclerView mSwipeRecyclerView;
    List<GoodsListResponseBean.DataBean.GoodslistBean> datas;
    RecycGridAdapter adapter;
    FrameLayout fr_label;
    LabelFlowLayout ll_labels;
    View nodataView;
    boolean isRefresh,isLoadMore,isFirst=true;

    @Override
    protected void initView() {
        mSwipeRecyclerView = ViewUtils.getView(activity,R.id.swipeRecyclerView);
        tv_title = ViewUtils.getView(activity, R.id.tv_title);
        nodataView = ViewUtils.getView(activity, R.id.nodataView);
        tv_verify = ViewUtils.getView(activity,R.id.tv_verify);
        tv_new = ViewUtils.getView(activity, R.id.tv_new);
        tv_price = ViewUtils.getView(activity, R.id.tv_price);
        tv_default = ViewUtils.getView(this, R.id.tv_default);
        fr_label = ViewUtils.getView(this,R.id.fr_label);
        ll_labels = ViewUtils.getView(this, R.id.ll_labels);
        iv_price_filtrate = ViewUtils.getView(activity, R.id.iv_price_filtrate);
        tv_condition = ViewUtils.getView(activity, R.id.tv_condition);
        dl_condition = ViewUtils.getView(activity, R.id.dl_drawer);

        if (!ViewUtils.isEmpty(name)) tv_title.setText(name);

        if (is_new == 1) {
            tv_new.setTextColor(getResources().getColor(R.color.text_black));

            tv_price.setTextColor(getResources().getColor(R.color.text_grey));
            iv_price_filtrate.setImageResource(R.drawable.price_grey);
        }
        if (is_new == -1) {
            tv_new.setTextColor(getResources().getColor(R.color.text_grey));
            tv_default.setTextColor(getResources().getColor(R.color.text_black));
            tv_price.setTextColor(getResources().getColor(R.color.text_grey));
            iv_price_filtrate.setImageResource(R.drawable.price_grey);
        }

        mSwipeRecyclerView.getSwipeRefreshLayout()
                .setColorSchemeColors(Color.RED);
        //set layoutManager
        GridLayoutManager manager = new GridLayoutManager(this,2);

        mSwipeRecyclerView.getRecyclerView().setLayoutManager(manager);
        datas = new ArrayList<>();
        adapter = new RecycGridAdapter(datas,this);
        mSwipeRecyclerView.setAdapter(adapter);
        mSwipeRecyclerView.setOnLoadListener(new SwipeRecyclerView.OnLoadListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                isLoadMore = false;
                pageNow = 0;
                initInfo();
            }

            @Override
            public void onLoadMore() {
                pageNow++;
                isLoadMore = true;
                isRefresh = false;
                initInfo();
            }
        });

        adapter.setmOnItemClickListener(new RecycGridAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(activity, ProductInfoActivity.class);
                intent.putExtra("name", datas.get(position).getGoods_name()).putExtra("goods_id", datas.get(position).getId());
                startActivity(intent);
            }
        });

        ConditionFragment fragment = new ConditionFragment();
        fragment.setArguments(getFragmentBundle());
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.fragment_container, fragment);
        ft.commit();

        fragment.setOnDataChangeListener(this);
    }

    private Bundle getFragmentBundle() {
        Bundle bundle = new Bundle();
        if (!TextUtils.isEmpty(brand_id)) {
            bundle.putString("brandId", brand_id);
            bundle.putString("brandName", name);
        }
        if (!TextUtils.isEmpty(cate_id)) {
            bundle.putString("categoeryId", cate_id);
            bundle.putString("categoeryName", name);
        }
        if (!TextUtils.isEmpty(keywords)) {
            bundle.putString("keyword", keywords);
        }

        //记录是分类的筛选(0)，还是品牌进入的筛选(1)
        if(!TextUtils.isEmpty(cate_id)){
            bundle.putInt("filterType", 0);
        }else{
            bundle.putInt("filterType", 1);
        }
        return bundle;
    }


    int pageNow = 0;
    /**
     * 1:is_new=1 0:is_new=0
     */
    int is_new = -1;
    /**
     * 0:is_new=0,sort="price",sort_type=0 降序  1:is_new=0,sort="price",sort_type=1 升序
     */
    int sort_type = 0;

    int minPrice = 0, maxPrice = 100000;

    GoodsListRequestFilter filter;
    @Override
    protected void initInfo() {
        super.initInfo();


        filter = new GoodsListRequestFilter(activity);
        if (!ViewUtils.isEmpty(keywords)) filter.requestBean.keywords = keywords;
        if (!ViewUtils.isEmpty(brand_id))
            filter.requestBean.brand_id = brand_id;
        if (!ViewUtils.isEmpty(cate_id))
            filter.requestBean.cate_id = cate_id;
        filter.requestBean.price_section = minPrice + "," + maxPrice;
        if (!TextUtils.isEmpty(years))
            filter.requestBean.years = years;
        if (!TextUtils.isEmpty(season))
            filter.requestBean.season = season;
        filter.requestBean.pageNow = String.valueOf(pageNow);
        if (is_new == 1) {
            filter.requestBean.is_new = "1";
            filter.requestBean.sort = "";
            filter.requestBean.sort_type = "0";
        } else if (is_new == 0) {
            filter.requestBean.is_new = "0";
            filter.requestBean.sort = "price";
            if (sort_type == 0) {
                filter.requestBean.sort_type = "0";
            } else if (sort_type == 1) {
                filter.requestBean.sort_type = "1";
            }
        } else {
            filter.requestBean.is_new = "0";
            filter.requestBean.sort = "";
            filter.requestBean.sort_type = "0";
        }
        filter.requestBean.version = AppUtils.getVersionCode(this)+"";
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<GoodsListResponseBean>() {
            @Override
            public void onSuccess(GoodsListResponseBean result) {

                if(result!=null && result.getData()!=null && result.getData().getLabels()!=null
                        && result.getData().getLabels().size()>0){
                    labels = result.getData().getLabels();
                    addLabel();
                }else{
                    fr_label.setVisibility(View.GONE);
                }
                if(result==null) {
                    result = new GoodsListResponseBean();
                }
                if(pageNow==0){
                    if(result.getData().getGoodslist().size()==0){
                        nodataView.setVisibility(View.VISIBLE);
                        mSwipeRecyclerView.setVisibility(View.GONE);
                    }
                }
                if(isFirst){
                    datas.addAll(result.getData().getGoodslist());
                    adapter.notifyDataSetChanged();
                    isFirst = false;
                    if(result.getData().getGoodslist().size()<20){
                        mSwipeRecyclerView.setLoadMoreEnable(false);
                    }
                    return;
                }
                if(isLoadMore ) {
                    datas.addAll(result.getData().getGoodslist());
                    isLoadMore = false;
                    if(result.getData().getGoodslist().size()==0){
                        mSwipeRecyclerView.onNoMore("一  End  一");
                    }else{
                        mSwipeRecyclerView.stopLoadingMore();
                        adapter.notifyDataSetChanged();
                    }
                    adapter.notifyDataSetChanged();
                    return;
                }else if(isRefresh){
                    if(result.getData().getGoodslist().size()<20){
                        mSwipeRecyclerView.setLoadMoreEnable(false);
                    }
                    if(result.getData().getGoodslist().size() == 0){
                        mSwipeRecyclerView.complete();
                        isRefresh = false;
                        return;
                    }

                    datas.clear();
                    datas.addAll(result.getData().getGoodslist());
                    isRefresh = false;
                    mSwipeRecyclerView.complete();
                    adapter.notifyDataSetChanged();
                    return;
                }else {
                    datas.clear();
                    datas.addAll(result.getData().getGoodslist());
                    adapter.notifyDataSetChanged();
                    return;
                }
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
            }
        });
    }

    List<String> labels;
    private void addLabel() {
        fr_label.setVisibility(View.VISIBLE);
        if(ll_labels.getChildCount()>0){
            ll_labels.removeAllViews();
        }
        for(int i = 0; i < labels.size(); i ++){
            View view = LayoutInflater.from(this).inflate(R.layout.item_tag, ll_labels,false);
            TextView tv_tag = (TextView) view.findViewById(R.id.tv_tag);
            tv_tag.setText(labels.get(i));
            ll_labels.addView(view);
        }
    }




    @Override
    protected void initEvent() {
        ViewUtils.getView(activity, R.id.iv_back).setOnClickListener(this);
        ViewUtils.getView(activity, R.id.tv_new).setOnClickListener(this);
        ViewUtils.getView(activity, R.id.rl_price).setOnClickListener(this);
        ViewUtils.getView(activity, R.id.tv_condition).setOnClickListener(this);
        ViewUtils.getView(activity, R.id.tv_default).setOnClickListener(this);
        tv_verify.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_condition:
                dl_condition.openDrawer(Gravity.RIGHT);
                break;
            case R.id.tv_new:
                changeNavDefaultStyle();
                initInfo();
                break;
            case R.id.tv_default:
                changeNavMyDefaultStyle();
                initInfo();
                break;
            case R.id.rl_price:
                changeNavPriceStyle();
                initInfo();
                break;
            case R.id.tv_verify:
                showShare();
                break;
        }
    }

    UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA share_media) {
            ToastUtils.showToast(share_media.toString());
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            ToastUtils.showToast(share_media.toString());
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            ToastUtils.showToast(share_media.toString());
        }
    };

    /**
     * 分享
     */
   /* UMSocialService mController;*/
    UMShareAPI mShareAPI = null;
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(getApplicationContext(), "Authorize succeed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getApplicationContext(), "Authorize fail", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getApplicationContext(), "Authorize cancel", Toast.LENGTH_SHORT).show();
        }
    };



    private void showShare() {

        getShareUrl();

    }


    private void getShareUrl() {
        StringBuffer str = null;
        if (null != EntryPageName.globalRequestBean && null != EntryPageName.globalRequestBean.getData() && null != EntryPageName.globalRequestBean.getData().getShare()
                &&null != EntryPageName.globalRequestBean.getData().getShare().getGoodslist()) {
            String baseUrl = EntryPageName.globalRequestBean.getData().getShare().getGoodslist();
            str = new StringBuffer(baseUrl);
        }


        if(filter!=null) {

            try {

                String keywords = URLEncoder.encode(filter.requestBean.keywords, "UTF-8");
                String season = URLEncoder.encode(filter.requestBean.season, "UTF-8");
                String name = URLEncoder.encode(tv_title.getText().toString(), "UTF-8");
                String secondname = URLEncoder.encode(name, "UTF-8");

                str.append("keywords="+keywords+"&"+
                        "cate_id="+filter.requestBean.cate_id+"&"+
                        "brand_id="+filter.requestBean.brand_id+"&"+
                        "is_new="+filter.requestBean.is_new+"&"+
//                        "relation_pos_id="+relation_pos_id+"&"+
                        "min="+minPrice+"&"+
                        "max="+maxPrice+"&"+
                        "season="+season+"&"+
                        "years="+filter.requestBean.years+"&"+
                        "zg_flag="+filter.requestBean.zg_flag+"&"+
                        "sort="+filter.requestBean.sort+"&"+
                        "sort_type="+filter.requestBean.sort_type+"&"+
                        "pageNow="+filter.requestBean.pageNow+"&"+
                        "pageSize="+filter.requestBean.pageSize+"&"+
                        "name="+secondname);

                MyShareUtils.showShare(tv_title.getText().toString(),"", new String(str),new String(str));
                LogUtils.e("fenxiangde url",new String(str));


            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);


    }

    private void changeNavDefaultStyle() {
        tv_new.setTextColor(getResources().getColor(R.color.text_black));
        tv_price.setTextColor(getResources().getColor(R.color.text_grey));
        tv_default.setTextColor(getResources().getColor(R.color.text_grey));
        iv_price_filtrate.setImageResource(R.drawable.price_grey);

        is_new = 1;
        pageNow = 0;
    }

    private void changeNavMyDefaultStyle() {
        tv_new.setTextColor(getResources().getColor(R.color.text_grey));
        tv_price.setTextColor(getResources().getColor(R.color.text_grey));
        tv_default.setTextColor(getResources().getColor(R.color.text_black));
        iv_price_filtrate.setImageResource(R.drawable.price_grey);
        is_new = -1;
        pageNow = 0;
    }

    private void changeNavPriceStyle() {
        tv_default.setTextColor(getResources().getColor(R.color.text_grey));
        if (is_new != 0) {
            tv_new.setTextColor(getResources().getColor(R.color.text_grey));
            tv_price.setTextColor(getResources().getColor(R.color.text_black));
            if (sort_type == 0) iv_price_filtrate.setImageResource(R.drawable.price_down);
            else if (sort_type == 1)
                iv_price_filtrate.setImageResource(R.drawable.price_up);

            is_new = 0;
            pageNow = 0;
        } else if (is_new == 0) {
            if (sort_type == 0) {
                sort_type = 1;
                iv_price_filtrate.setImageResource(R.drawable.price_up);
            } else {
                sort_type = 0;
                iv_price_filtrate.setImageResource(R.drawable.price_down);
            }
            pageNow = 0;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(activity, ProductInfoActivity.class);
        intent.putExtra("goods_id", datas.get(position).getId());
        startActivity(intent);

    }

    @Override
    public void onChange(Condition condition) {
        if (TextUtils.equals(years, condition.getYearId())
                && TextUtils.equals(season, condition.getSeasonId())
                && TextUtils.equals(cate_id, condition.getCategoeryId())
                && TextUtils.equals(brand_id, condition.getBrandId())
                && TextUtils.equals(String.valueOf(minPrice), condition.getMin())
                && TextUtils.equals(String.valueOf(maxPrice), condition.getMax())
                && TextUtils.equals(keywords,condition.getKeyword()))
            return;
        cate_id = condition.getCategoeryId();
        brand_id = condition.getBrandId();
        season = condition.getSeasonId();
        years = condition.getYearId();
        name = condition.getBrandName();
        keywords=condition.getKeyword();
        if (TextUtils.isEmpty(name))
            tv_title.setText("全部品牌");
        else
            tv_title.setText(name);
        if (TextUtils.isEmpty(condition.getMin())) {
            minPrice = 0;
        } else {
            minPrice = Integer.valueOf(condition.getMin());
        }
        if (TextUtils.isEmpty(condition.getMax())) {
            maxPrice = 100000;
        } else {
            maxPrice = Integer.valueOf(condition.getMax());
        }

        pageNow = 0;
        datas.clear();
        initInfo();
    }

    @Override
    public void close() {
        dl_condition.closeDrawer(Gravity.RIGHT);
    }
}
